import 'dart:async';

import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/pages/login/widgets/captcha.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:quiver/strings.dart';

class LoginPhone extends StatefulWidget {
  LoginPhone({Key key}) : super(key: key);

  _LoginPhoneState createState() => _LoginPhoneState();
}

class _LoginPhoneState extends State<LoginPhone> {
  static Map phone = {"value": '', "verify": true};
  static Map captcha = {"value": '', "verify": true};
  static Map message = {"value": '', "verify": true};

  SharedPreferences prefs;

  /// 开始倒计时 时间
  int startTime;

  /// 当前倒计时 时间
  int countDownTime = 0;

  /// 总倒计时时长
  final int speed = 60;

  Timer _timer;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      startTime = prefs.getInt('startTime');
      int nowTime = G.getTime();
      if (startTime != null && startTime > 0) {
        if (nowTime - startTime > 60) {
          prefs.remove('startTime');
        } else {
          countDown();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  /// 获取验证码
  getMsgCode() async {
    try {
      var res = await G.req.user.sendMessage(telephoneNumber: phone['value']);
      if (res.data == null) return;
      G.toast('获取验证码成功');
      startTime = G.getTime();
      countDown();
    } catch (e) {
      G.toast('获取验证码失败');
    }
  }

  /// 倒计时
  countDown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      int nowTime = G.getTime();
      int result = speed - (nowTime - startTime);
      if (result < 0) {
        prefs.remove('startTime');
        _timer?.cancel();
      }

      setState(() {
        countDownTime = result;
      });
    });
  }

  /// 登录
  _submit() async {
    if (!isNotBlank(phone['value'])) {
      G.toast('手机号不能为空');
      return;
    }
    // if (!isNotBlank(captcha['value'])) {
    //   G.toast('图形验证码不能为空');
    //   return;
    // }
    if (!isNotBlank(message['value'])) {
      G.toast('短信不能为空');
      return;
    }
    
    print("$phone");
    print("$captcha");
    print("$message");
  }

  getUserDetail(String token) async {
    var res = await G.req.user.detail();

    var data = res.data;

    Map json = data['data']['base'];
    json['token'] = token;

    G.user.init(json);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: customAppbar(context: context, borderBottom: false),
      body: Container(
          color: hex('#fff'),
          padding: EdgeInsets.only(left: 25, right: 25, top: 20),
          height: G.screenHeight(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('手机号登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold)),

                  Container(
                    height: 55,
                    margin: EdgeInsets.only(top: 20),
                    decoration: BoxDecoration(border: G.borderBottom()),
                    child: TextField(
                      keyboardType: TextInputType.phone,
                      decoration: InputDecoration(
                          counterText: "",
                          border: InputBorder.none,
                          hintText: '输入手机号',
                          hintStyle: TextStyle(
                            color: rgba(163, 163, 163, 1),
                            fontSize: 16,
                          )),
                      onChanged: (e) {
                        RegExp regExp = RegExp(r"1[d]{9}$");
                        setState(() {
                          phone['value'] = e;
                          phone['verify'] = regExp.hasMatch(e);
                        });
                      },
                    ),
                  ),
                  // Container(
                  //   height: 55,
                  //   decoration: BoxDecoration(border: G.borderBottom()),
                  //   child: Row(
                  //     children: <Widget>[
                  //       Flexible(
                  //         child: TextField(
                  //           // maxLength: 4,
                  //           keyboardType: TextInputType.text,
                  //           decoration: InputDecoration(
                  //               counterText: '',
                  //               border: InputBorder.none,
                  //               hintText: '输入图形验证码',
                  //               hintStyle: TextStyle(
                  //                 color: rgba(163, 163, 163, 1),
                  //                 fontSize: 16,
                  //               )),
                  //           onChanged: (e) {
                  //             setState(() {
                  //               captcha['value'] = e;
                  //               captcha['verify'] =
                  //                   e.length == 4 ? true : false;
                  //             });
                  //           },
                  //         ),
                  //       ),
                  //       Container(
                  //         height: 25,
                  //         decoration: BoxDecoration(
                  //             border: Border(
                  //                 left: BorderSide(
                  //                     color: rgba(242, 242, 242, 1)))),
                  //       ),
                  //       Captcha()
                  //     ],
                  //   ),
                  // ),

                  /// 验证码
                  Container(
                    height: 55,
                    decoration: BoxDecoration(border: G.borderBottom()),
                    child: Row(
                      children: <Widget>[
                        Flexible(
                          child: TextField(
                            maxLength: 6,
                            keyboardType: TextInputType.number,
                            decoration: InputDecoration(
                                counterText: '',
                                border: InputBorder.none,
                                hintText: '输入验证码',
                                hintStyle: TextStyle(
                                  color: rgba(163, 163, 163, 1),
                                  fontSize: 16,
                                )),
                            onChanged: (e) {
                              setState(() {
                                message['value'] = e;
                                message['verify'] =
                                    e.length == 6 ? true : false;
                              });
                            },
                          ),
                        ),
                        Container(
                          height: 25,
                          decoration: BoxDecoration(
                              border: Border(
                                  left: BorderSide(
                                      color: rgba(242, 242, 242, 1)))),
                        ),
                        buildGetEmailCode()
                      ],
                    ),
                  ),

                  /// 确认
                  Container(
                      margin: EdgeInsets.only(top: 25),
                      child: AButton.normal(
                        width: double.infinity,
                        child: Text('登录'),
                        color: hex('#fff'),
                        bgColor: rgba(42, 125, 250, 1),
                        borderColor: rgba(136, 175, 213, 1),
                        onPressed: _submit,
                      )),

                  /// 协议
                  GestureDetector(
                    onTap: () => {G.pushNamed('/user_agreement')},
                    child: Container(
                      margin: EdgeInsets.only(top: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            '点击登录，即表示同意',
                            style: TextStyle(
                                fontSize: 12, color: rgba(51, 51, 51, 1)),
                          ),
                          Container(
                              child: Text.rich(TextSpan(children: [
                            TextSpan(
                                text: '《隐私政策》',
                                style: TextStyle(
                                    fontSize: 12,
                                    color: rgba(25, 109, 236, 1))),
                            TextSpan(
                                text: '及',
                                style: TextStyle(
                                    fontSize: 12, color: rgba(51, 51, 51, 1))),
                            TextSpan(
                                text: '《服务协议》',
                                style: TextStyle(
                                    fontSize: 12, color: rgba(25, 109, 236, 1)))
                          ]))),
                        ],
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 14),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        AButton.normal(
                            onPressed: () {
                              G.pop();
                            },
                            child: Text(
                              '账号密码登录',
                              style: TextStyle(
                                  fontSize: 16, color: rgba(51, 51, 51, 1)),
                            ))
                      ],
                    ),
                  )
                ],
              ),
              Container(
                  // color: Colors.blue,
                  height: 220,
                  padding: EdgeInsets.symmetric(vertical: 40),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                                height: 1,
                                width: 80,
                                color: rgba(235, 235, 235, 1)),
                            Text(
                              '其他方式登录',
                              style: TextStyle(
                                  color: rgba(136, 135, 135, 1), fontSize: 14),
                            ),
                            Container(
                                height: 1,
                                width: 80,
                                color: rgba(235, 235, 235, 1)),
                          ]),
                      Container(
                        margin: EdgeInsets.only(top: 30),
                        child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Image.asset('lib/assets/images/weixin.png',
                                  width: 36, height: 36, fit: BoxFit.contain),
                              Image.asset('lib/assets/images/weibo.png',
                                  width: 36, height: 36, fit: BoxFit.contain),
                              Image.asset('lib/assets/images/qq.png',
                                  width: 36, height: 36, fit: BoxFit.contain),
                            ]),
                      )
                    ],
                  ))
            ],
          )),
    );
  }

  /// 获取验证码
  Container buildGetEmailCode() {
    return Container(
      child: AButton.normal(
          child: Text(countDownTime <= 0
              ? "获取验证码"
              : countDownTime < 10
                  ? '0$countDownTime'
                  : '$countDownTime'),
          color: phone['verify'] && phone['value'] != null
              ? rgba(25, 109, 236, 1)
              : rgba(166, 166, 166, 1),
          onPressed: () {
            if (countDownTime > 0) return;
            getMsgCode();
          }),
    );
  }
}
